package edu.uwm.RobberKnight.View;

import java.awt.Color;
import java.awt.Graphics;

/*
 * A fire work that will fly and explode into a display of colors.
 */
public class Firework {
	
	private int _blastRadius;
	private int _trailLength;
	private int _particles;
	private int _vertDistance;
	//pixels per second
	private int _speed;
	private int _particleSpeed;
	private long _elapsedTime;
	private boolean _exploded;
	private Color _color;

	//state tracking variables.
	private float _x;
	private float _y;
	private float _particleDistance;
	//0 to 255
	private int _alpha = 255;
	private boolean _fade;
	private long _fadeStart;
	private boolean _finished;
	
	public Firework(int x, int y, int particles, int speed, int particleSpeed, int vertDistance, int blastRadius, int trailLength, Color color) {
		_particles = particles;
		_speed = speed;
		_particleSpeed = particleSpeed;
		_vertDistance = vertDistance;
		_x = x;
		_y = y;
		_blastRadius = blastRadius;
		_trailLength = trailLength;
		_color = color;
	}
	
	/*
	 * Return whether the firework has finished its display.
	 */
	public boolean isFinished() {
		return _finished;
	}
	
	/*
	 * Update the firework based on the time elapsed since the last update.
	 */
	public void updateState(long time) {
		_elapsedTime += time;
		if(!_exploded) {
			_y -= (time/1000f) * _speed;
			if(_y <= _vertDistance) {
				_exploded = true;
			}
		} else {
			_particleDistance += (time/1000f) * _particleSpeed;
			if(!_fade && _particleDistance > _blastRadius) {
				_fade = true;
				_fadeStart = _elapsedTime;
			}
			if(_fade) {
				//takes about two seconds to fade.
				_alpha = 255 - (int)((_elapsedTime - _fadeStart)/1000f * 125);
			}
		}
		if(_alpha <= 0)
			_finished = true;
	}
	
	/*
	 * Draw the fire work.
	 */
	public void draw(Graphics g, int offsetX, int offsetY) {
		if(_alpha >= 0) {
			Color color = new Color(_color.getRed(), _color.getGreen(), _color.getBlue(), _alpha);
			g.setColor(color);
			if(!_exploded) {
				g.fillOval((int)(_x - offsetX), (int)(_y - offsetY), 7, 7);
			} else {
				double angle = (2 * Math.PI) / _particles;
				for(int i = 0; i < _particles; i++) {
					int x = (int) (_particleDistance * Math.cos(angle * i) + _x - offsetX);
					int y = (int) (_particleDistance * Math.sin(angle * i) + _y - offsetY);
					g.fillOval(x, y, 2, 2);
					
					double xTrail = _trailLength * Math.cos(angle * i);
					double yTrail = _trailLength * Math.sin(angle * i);
					if(_particleDistance < _trailLength) {
						xTrail = _particleDistance * Math.cos(angle * i);;
						yTrail = _particleDistance * Math.sin(angle * i);
					}
					g.drawLine(x, y, (int)(x - xTrail), (int)(y - yTrail));
				}
			}
		}
	}

}
